﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Net;
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;

namespace XtyWallpaper
{
    public class AppUpdate
    {
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni
            );

        #region 定义，写注册表，自启动
        private const string REGKEYAutoRun = @"SoftWare\MicroSoft\Windows\CurrentVersion\Run";//开机运行的注册表路径
        private const string REGKEYIsFirstRun = @"SoftWare\XtyWallpaper";
        private const string REGKEYDesktopPath = @"Control Panel\Desktop";
        private const string IsFirstRunKeyName = "IsFirstRun";
        #endregion

        #region 并写注册表自启动
        public bool IsFirstRun = true;
        public void Init()
        {
            int key = Convert.ToInt32(GetRegistValue(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName));
            if (key == 2)
            {
                SetRegist(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName, "1");
                key = 1;
            }

            IsFirstRun = Convert.ToBoolean(key);

            if (IsFirstRun) //第一次启动
            {
                SetRegist(Registry.LocalMachine, REGKEYAutoRun, "XtyWallpaper", "\"" + GetMapPath("XtyWallpaper.exe") + "\"");//写到注册表中，开机自启动
                SetRegist(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName, "0");

                string deskImgPath = GetMapPath("Wallpaper.bmp");
                SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "Wallpaper", deskImgPath);
                SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "ConvertedWallpaper", deskImgPath);
                SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "OriginalWallpaper", deskImgPath);
            }
        }
        /// <summary>
        /// 卸载
        /// </summary>
        public void Uninst()
        {
            DeleteRegist(Registry.LocalMachine, REGKEYAutoRun, "XtyWallpaper");
            DeleteRegist(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName);

            string defaultImg = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Microsoft\\Windows\\Wallpaper1.bmp";
            //win 7以上
            if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 0)
            {
                defaultImg = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\Windows\\Themes\\TranscodedWallpaper.jpg";
            }

            SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "Wallpaper", defaultImg);
            SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "ConvertedWallpaper", defaultImg);
            SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "OriginalWallpaper", defaultImg);

            SystemParametersInfo(20, 0, defaultImg, 0x2);
        }
        /// <summary>
        /// 删除注册表值节点
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="REGKEY"></param>
        /// <param name="name"></param>
        /// <param name="Path"></param>
        void DeleteRegist(RegistryKey regKey, string REGKEY, string name)
        {
            try
            {
                RegistryKey reg = regKey.OpenSubKey(REGKEY, true);
                if (reg != null)
                {
                    reg.DeleteValue(name);
                    reg.Close();
                }
            }
            catch { }
        }
        /// <summary>
        /// 写注册表值
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="REGKEY"></param>
        /// <param name="name"></param>
        /// <param name="Path"></param>
        void SetRegist(RegistryKey regKey, string REGKEY, string name, string Path)
        {
            try
            {
                RegistryKey reg = regKey.OpenSubKey(REGKEY, true);

                if (reg == null)
                {
                    reg = regKey.CreateSubKey(REGKEY);
                }
                reg.SetValue(name, Path);
                reg.Close();
            }
            catch { }
        }
        /// <summary>
        /// 获取注册表值
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="REGKEY"></param>
        /// <param name="name"></param>
        /// <param name="Path"></param>
        string GetRegistValue(RegistryKey regKey, string REGKEY, string name)
        {
            RegistryKey reg = regKey.OpenSubKey(REGKEY, true);

            if (reg != null)
            {
                string value = reg.GetValue(name, "2").ToString();
                reg.Close();
                return value;
            }
            else
                return "2";
        }
        #endregion

        string HTMLSubstring(string html, string startLab, string endLab)
        {
            string result = string.Empty;
            try
            {
                int start = html.IndexOf(startLab);
                int end = html.IndexOf(endLab, start);
                if (end > start)
                {
                    start = start + startLab.Length;
                    int len = end - start;
                    result = html.Substring(start, len);
                }
            }
            catch { }

            return result;
        }

        string GetPage(string sourceURL, string charset)
        {
            string html = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceURL);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705)";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(charset)))
                    {
                        html = reader.ReadToEnd();
                    }
                }
            }
            catch { }

            return html;
        }

        void DownloadFile(string fileURL, string savePath)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileURL);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705)";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (FileStream outputStream = new FileStream(savePath, FileMode.Create))
                    {
                        using (Stream fileStream = response.GetResponseStream())
                        {
                            int bufferSize = 2048;
                            int readCount;
                            byte[] buffer = new byte[bufferSize];
                            readCount = fileStream.Read(buffer, 0, bufferSize);
                            while (readCount > 0)
                            {
                                outputStream.Write(buffer, 0, readCount);
                                readCount = fileStream.Read(buffer, 0, bufferSize);
                            }
                            fileStream.Dispose();
                            outputStream.Dispose();
                            response.Close();
                        }
                    }
                }
            }
            catch { }
        }

        public string GetMapPath(string fileName)
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
        }

        /// <summary>
        /// 更新程序
        /// </summary>
        public void Update()
        {
            string sourceURL = "http://www.xiaotuya.com/xtywallpaper/update.aspx";
            string downloadURL = "http://www.xiaotuya.com/xtywallpaper/download/";
            string charset = "utf-8";
            string pageContent = GetPage(sourceURL, charset);
            string[] versionArray = pageContent.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (versionArray.Length > 1)
            {
                bool isUpdate = true;
                string version = versionArray[0];

                string versionFile = GetMapPath("说明.txt");
                if (File.Exists(versionFile))
                {
                    string[] versionLocal = File.ReadAllLines(versionFile);
                    if (versionLocal.Length > 0 && version == versionLocal[0])
                    {
                        isUpdate = false;
                    }
                }

                if (isUpdate)
                {
                    
                    for (int i = 1; i < versionArray.Length; i++)
                    {
                        string filename = versionArray[i];
                        string savePath = GetMapPath(filename);
                        string fileURL = downloadURL+ filename;
                        DownloadFile(fileURL, savePath);
                    }
                }
            }

            try
            {
                System.Diagnostics.Process.Start(GetMapPath("XtyDesktop.exe"));
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                Console.WriteLine("系统找不到指定的文件。/r{0}", ex.ToString());
            }
        }
    }
}
